import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_base/pages/home/home_logic.dart';
import 'package:flutter_base/pages/home/model/model_test_psychology.dart';
import 'package:flutter_base/utils/utils_other.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'dart:ui';
import 'package:flutter_base/base/widget/base_get_builder.dart';
import 'package:flutter_base/widgets/appbar/common_app_bar.dart';
import 'package:flutter_base/generated/assets.dart';
import 'package:flutter_base/widgets/image/auto_image.dart';
import 'package:flutter_base/widgets/image/image_view.dart';
import 'package:flutter_base/config/app_color.dart';
import 'package:flutter_base/config/app_config.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_base/widgets/test_card/test_card_widget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:flutter_base/config/app_routes.dart';
// import '../main/home/home_logic.dart';

class HomePage extends StatelessWidget {
  final logic = Get.put(HomeLogic());

  HomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
// logic.refreshController.loadComplete();
// logic.refreshController.refreshCompleted();

    return BaseGetBuilder<HomeLogic>(
      backgroundColor: AppColor.colorF5F7FA,
      builder: (_) {
        return Stack(
          children: [
            Obx(() {

              return Positioned(
                  top: min(-logic.scrollPixels.value, 0),
                  left: 0,
                  right: 0,
                  child: _buildTopSection());
            }),

            Positioned.fill(
                child: SmartRefresher(
              controller: logic.refreshController,
              enablePullDown: true,
              enablePullUp: true,
              onRefresh: () {
                logic.loadPopularTests(refresh: true);
                logic.loadRecommendData();
                // _refreshController.refreshCompleted();
              },
              onLoading: () {
                logic.page++;
                logic.loadPopularTests(refresh: false);
              },
              child: CustomScrollView(
                controller: logic.scrollController,
                slivers: [
                  // 顶部部分
                  // _buildTopSection(),
                  // 268.verticalSpaceFromWidth,
                  SliverToBoxAdapter(
                    child: SizedBox(
                      height: 268.w,
                    ),
                  ),
                  _buildTitle(
                    "Today's recommendations",
                    Assets.homeRecommend,
                  ),

                  // 推荐部分
                  _buildRecommendSection(),
                  _buildTitle(
                    "Popular Tests",
                    Assets.homePopular,
                  ),
                  // 底部列表部分 - 心理测试卡片
                  _buildBottomListSection(),
                ],
              ),
            ))
          ],
        );
        // return SmartRefresher(
        //   controller: logic.refreshController,
        //   enablePullDown: true,
        //   enablePullUp: true,
        //   onRefresh: () {
        //     logic.loadPopularTests(refresh: true);
        //     logic.loadRecommendData();
        //     // _refreshController.refreshCompleted();
        //   },
        //   onLoading: () {
        //     logic.page++;
        //     logic.loadPopularTests(refresh: false);
        //   },
        //   child: CustomScrollView(
        //     slivers: [
        //       // 顶部部分
        //       _buildTopSection(),
        //
        //       _buildTitle(
        //         "Today's recommendations",
        //         Assets.homeRecommend,
        //       ),
        //
        //       // 推荐部分
        //       _buildRecommendSection(),
        //       _buildTitle(
        //         "Popular Tests",
        //         Assets.homePopular,
        //       ),
        //       // 底部列表部分 - 心理测试卡片
        //       _buildBottomListSection(),
        //     ],
        //   ),
        // );
      },
    );
  }

  Widget _buildTitle(String title, String icon) {
    return SliverToBoxAdapter(
      child: SizedBox(
        height: 32.w,
        child: Row(
          children: [
            16.horizontalSpace,
            AutoImage(
              icon,
              width: 20.w,
            ),
            4.horizontalSpace,
            Expanded(
                child: Text(
              title,
              style: TextStyle(
                  color: AppColor.color0C0A09,
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w600),
            ))
          ],
        ),
      ).marginOnly(top: 20.w, bottom: 12.w),
    );
  }

  // 顶部部分
  Widget _buildTopSection() {
    return SizedBox(
      width: double.infinity,
      height: 268.w,
      // color: AppColor.colorF5F7FA,
      child: Stack(
        children: [
          // AI数字人组件
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            bottom: 16.w,
            child: Container(
                width: 375.w,
                height: 240.w,
                decoration: const BoxDecoration(
                  image: DecorationImage(
                      image: AssetImage(
                        Assets.homeTopBg,
                      ),
                      fit: BoxFit.cover),
                ),
                child: Align(
                  alignment: Alignment.bottomRight,
                  child: AutoImage(
                    Assets.homeDigitalHuman,
                    width: 200.w,
                    height: 200.w,
                    fit: BoxFit.cover,
                  ),
                )),
          ),

          // 头像和通知数量
          Positioned(
            top: 50.w,
            left: 16.w,
            bottom: 0,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    // 头像
                    Container(
                      width: 36.w,
                      height: 36.w,
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(33.w),
                      ),
                      child: Center(
                        child: AutoImage(
                          Assets.homeTopRobot, // 使用测试图片
                          width: 28.w,
                          height: 28.w,
                          fit: BoxFit.cover,
                        ),
                      ),
                    ),

                    // 通知数量徽章
                    Transform.translate(
                      offset: Offset(-16.w, -16.w),
                      child: Container(
                        width: 16.w,
                        height: 16.w,
                        decoration: BoxDecoration(
                          color: AppColor.colorDD5E9B,
                          borderRadius: BorderRadius.circular(52.w),
                          border: Border.all(
                            color: Colors.white,
                            width: 1.w,
                          ),
                        ),
                        child: Center(
                          child: Text(
                            '12',
                            style: TextStyle(
                              fontSize: 10.sp,
                              fontWeight: FontWeight.w500,
                              color: Colors.white,
                              fontFamily: 'Outfit',
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 16.w),
                Text(
                  'HI, I am an AI digital person',
                  style: TextStyle(
                    fontSize: 12.sp,
                    fontWeight: FontWeight.w400,
                    color: AppColor.color7F909E,
                    fontFamily: 'Outfit',
                  ),
                ),

                SizedBox(height: 6.w),

                // 主要文字
                Text(
                  'How can I assist you?',
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w700,
                    color: AppColor.color0C0A09,
                    fontFamily: 'Outfit',
                  ),
                ),

                SizedBox(height: 14.w),

                // 提问按钮
                GestureDetector(
                  onTap: () => logic.onTalkNowTap(),
                  child: Container(
                    padding:
                        EdgeInsets.symmetric(horizontal: 24.w, vertical: 8.w),
                    decoration: BoxDecoration(
                      gradient: const LinearGradient(
                        colors: [AppColor.color63FFFA, AppColor.colorF59EFF],
                        begin: Alignment.topLeft,
                        end: Alignment.bottomRight,
                      ),
                      borderRadius: BorderRadius.circular(40.w),
                      border: Border.all(
                        color: Colors.white,
                        width: 1.w,
                      ),
                    ),
                    child: Text(
                      'Ask a question',
                      style: TextStyle(
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w600,
                        color: AppColor.color0C0A09,
                        fontFamily: 'Outfit',
                      ),
                    ),
                  ),
                ),
                const Spacer(),
                GestureDetector(
                  onTap: () => logic.onSearchTap(),
                  child: Container(
                    width: 343.w,
                    height: 44.w,
                    padding:
                        EdgeInsets.symmetric(horizontal: 12.w, vertical: 10.w),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(40.w),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.05),
                          blurRadius: 10.w,
                          offset: Offset(0, 2.w),
                        ),
                      ],
                    ),
                    child: Row(
                      children: [
                        // 搜索图标
                        AutoImage(
                          Assets.homeTopSearch,
                          width: 20.w,
                          height: 20.w,
                          color: AppColor.color7F909E,
                        ),
                        SizedBox(width: 8.w),
                        // 搜索文本
                        Text(
                          'Search for a test',
                          style: TextStyle(
                            fontSize: 14.sp,
                            fontWeight: FontWeight.w500,
                            color: AppColor.color7F909E,
                            fontFamily: 'Outfit',
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 推荐部分
  Widget _buildRecommendSection() {
    return SliverToBoxAdapter(
      child: SizedBox(
        height: 180.w,
        child: ListView.builder(
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          scrollDirection: Axis.horizontal,
          itemCount: logic.recommendTests.length,
          itemBuilder: (context, index) {
            return _buildRecommendCard(index);
          },
        ),
      ),
    );
  }

  // 推荐卡片
  Widget _buildRecommendCard(int index) {
    // 获取推荐测试数据
    final test = logic.recommendTests[index];

    // 根据索引设置不同的渐变色
    List<Color> gradientColors;
    switch (index % 3) {
      case 0:
        gradientColors = [Color(0xFF0072FF), Color(0xFF0AF662)];
        break;
      case 1:
        gradientColors = [Color(0xFFFC7F5F), Color(0xFFFB7FFF)];
        break;
      case 2:
        gradientColors = [Color(0xFF9B64E4), Color(0xFFB7D0FF)];
        break;
      default:
        gradientColors = [Color(0xFF0072FF), Color(0xFF0AF662)];
    }

    // 格式化价格显示
    String price = '免费';
    String originalPrice = '';
    if (test.price != null && test.price! > 0) {
      price = '\$${test.price}';
      if (test.discountPrice != null &&
          test.discountPrice! > 0 &&
          test.discountPrice! < test.price!) {
        originalPrice = '\$${test.discountPrice}';
      }
    }

    // 获取评分和参与人数
    String rating = test.star != null ? test.star.toString() : '4.5';
    String participants = test.total != null ? '${test.total}+' : '1.2k+';

    return GestureDetector(
      onTap: () => logic.onRecommendCardTap(index, test.name ?? ''),
      child: Container(
        width: 156.w,
        height: 180.w,
        margin: EdgeInsets.only(right: 8.w),
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: gradientColors,
          ),
          borderRadius: BorderRadius.circular(20.w),
        ),
        child: Stack(
          children: [
            // 顶部内容区域
            Positioned(
              top: 16.w,
              left: 12.w,
              right: 12.w,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 标题
                  Text(
                    test.name ?? '',
                    style: TextStyle(
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w500,
                      color: Colors.white,
                      fontFamily: 'Outfit',
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),

                  SizedBox(height: 6.w),

                  // 副标题
                  Text(
                    test.desc ?? '',
                    style: TextStyle(
                      fontSize: 10.sp,
                      fontWeight: FontWeight.w400,
                      color: Colors.white.withOpacity(0.6),
                      fontFamily: 'Outfit',
                      letterSpacing: 0.2,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),

                  SizedBox(height: 6.w),

                  // 用户头像和参与人数
                  Row(
                    children: [
                      // 头像组
                      SizedBox(
                        width: 36.w,
                        height: 16.w,
                        child: Stack(
                          children: [
                            // 第一个头像
                            Container(
                              width: 16.w,
                              height: 16.w,
                              decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(19.2.w),
                                border: Border.all(
                                    color: Colors.white, width: 0.5.w),
                              ),
                              child: ClipRRect(
                                borderRadius: BorderRadius.circular(19.2.w),
                                child: ImageView(
                                  imageUrl: '${AppConfig.testImage}',
                                  width: 16.w,
                                  height: 16.w,
                                  fit: BoxFit.cover,
                                ),
                              ),
                            ),

                            // 第二个头像
                            Positioned(
                              left: 10.w,
                              child: Container(
                                width: 16.w,
                                height: 16.w,
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(19.2.w),
                                  border: Border.all(
                                      color: Colors.white, width: 0.5.w),
                                ),
                                child: ClipRRect(
                                  borderRadius: BorderRadius.circular(19.2.w),
                                  child: ImageView(
                                    imageUrl: '${AppConfig.testImage}',
                                    width: 16.w,
                                    height: 16.w,
                                    fit: BoxFit.cover,
                                  ),
                                ),
                              ),
                            ),

                            // 第三个头像
                            Positioned(
                              left: 20.w,
                              child: Container(
                                width: 16.w,
                                height: 16.w,
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(19.2.w),
                                  border: Border.all(
                                      color: Colors.white, width: 0.5.w),
                                ),
                                child: ClipRRect(
                                  borderRadius: BorderRadius.circular(19.2.w),
                                  child: ImageView(
                                    imageUrl: '${AppConfig.testImage}',
                                    width: 16.w,
                                    height: 16.w,
                                    fit: BoxFit.cover,
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),

                      SizedBox(width: 4.w),

                      // 参与人数

                      Text(
                        '${UtilsOther.formatNumberCard(test.total ?? 0)}+',
                        style: TextStyle(
                          fontSize: 12.sp,
                          fontWeight: FontWeight.w400,
                          color: Colors.white,
                          fontFamily: 'Outfit',
                          letterSpacing: 0.06,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),

            // 底部价格和评分区域
            Positioned(
              bottom: 0,
              left: 0,
              right: 0,
              child: Container(
                height: 36.w,
                padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.w),
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.6),
                  // borderRadius: BorderRadius.circular(6.w),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    // 价格部分
                    Row(
                      children: [
                        // 当前价格
                        Text(
                          price,
                          style: TextStyle(
                            fontSize: 16.sp,
                            fontWeight: FontWeight.w700,
                            color: price == '免费'
                                ? Color(0xFF42B983) // Free显示绿色
                                : Color(0xFFFF6F00), // 价格显示橙色
                            fontFamily: 'Outfit',
                          ),
                        ),

                        // 原价（如果有）
                        if (originalPrice.isNotEmpty) ...[
                          SizedBox(width: 4.w),
                          Text(
                            originalPrice,
                            style: TextStyle(
                              fontSize: 10.sp,
                              fontWeight: FontWeight.w400,
                              color: AppColor.color0C0A09.withOpacity(0.16),
                              fontFamily: 'Outfit',
                              decoration: TextDecoration.lineThrough,
                            ),
                          ),
                        ],
                      ],
                    ),

                    // 评分部分
                    Row(
                      children: [
                        // 星星图标 - 使用自定义颜色而不是Icon组件
                        Container(
                          width: 14.w,
                          height: 14.w,
                          child: Icon(
                            Icons.star,
                            size: 14.w,
                            color: Color(0xFFFFB800),
                          ),
                        ),

                        SizedBox(width: 4.w),

                        // 评分
                        Text(
                          rating,
                          style: TextStyle(
                            fontSize: 12.sp,
                            fontWeight: FontWeight.w500,
                            color: AppColor.color0C0A09,
                            fontFamily: 'Outfit',
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 底部列表部分 - 心理测试卡片
  Widget _buildBottomListSection() {
    return SliverPadding(
      padding: EdgeInsets.symmetric(
        horizontal: 16.w,
      ),
      sliver: SliverGrid(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2, // 每行2个
          mainAxisSpacing: 12.w, // 主轴间距
          crossAxisSpacing: 12.w, // 交叉轴间距
          childAspectRatio: 165 / 179.0, // 宽高比
        ),
        delegate: SliverChildBuilderDelegate(
          (context, index) {
            // 使用从接口获取的数据
            final test = logic.popularTests[index];
            return TestCardWidget(
              model: test,
              // onTap: () => logic.onTestCardTap(test),
            );
          },
          childCount: logic.popularTests.length,
        ),
      ),
    );
  }
}
